<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="../../plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../plugins/datatables/css/jquery.dataTables.css">
    <link rel="stylesheet" href="../../plugins/font-awesome/css/font-awesome.min.css" media="all" />
    <link rel="stylesheet" href="../../css/rmp.css" media="all">
</head>
<body>
<div class="layui-fluid">
    <blockquote class="layui-elem-quote layui-quote-nm rmp-monitoring-btn-tools">
        <button class="layui-btn">数据分析</button>
        <button class="layui-btn">高级查询</button>
        <button class="layui-btn"><i class="fa fa-download"> 导出到EXCEL</i></button>
        <button class="layui-btn layui-btn-danger layui-hide">返回文件列表</button>
        <button class="layui-btn layui-btn-danger layui-hide">查看数据视图</button>
        <span class="rmp-serverInfo-btn-tools-right">
            <div class="layui-inline">
                <button class="layui-btn"><i class="layui-icon">&#x1002;</i></button>
            </div>
        </span>
    </blockquote>
    <div class="rmp-report-advanced-query layui-hide">
        <form class="layui-form layui-form-pane" action="">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="width: 100px;">服务器IP</label>
                    <div class="layui-input-inline" style="width: 200px;">
                        <input type="text" name="host" placeholder="IP" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" style="width: 100px;">标签</label>
                    <div class="layui-input-inline" style="width: 200px;">
                        <input type="text" name="tags" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" style="width: 100px;">开始时间</label>
                    <div class="layui-input-inline" style="width: 300px;">
                        <input type="text" name="startTime" autocomplete="off" class="layui-input" lay-datetime>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" style="width: 100px;">结束时间</label>
                    <div class="layui-input-inline" style="width: 300px;">
                        <input type="text" name="lastTime" autocomplete="off" class="layui-input" lay-datetime>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layui-btn-lightgreen" lay-submit lay-filter="advanced-query-submit">搜索</button>
                </div>
            </div>
        </form>
    </div>
    <hr>
    <div>
        <div id="rmp-report-history-table">
            <table class="layui-table" lay-skin="line row" >
                <thead>
                <tr>
                    <th><input type="checkbox"></th>
                    <th>#</th>
                    <th>文件名</th>
                    <th>服务器</th>
                    <th>记录总数</th>
                    <th>导出时间</th>
                    <th>文件大小</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
        <div id="rmp-report-monitoring-view" class="layui-hide">
            <div class="layui-fluid">
                <div class="rmp-monitoring-content">
                    <div class="layui-collapse">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../../plugins/jquery.js"></script>
<script src="../../plugins/layui/layui.js"></script>
<script src="../../plugins/datatables/js/jquery.dataTables.js"></script>
<script src="../../plugins/Echarts/echarts.min.js"></script>
<script src="../../plugins/Echarts/shine.js"></script>
<script src="../../js/global.js"></script>
<script>
    var globalLoadIndex;
    var viewInstances = {};
    var fileData = {};
    layui.use(['element', 'form', 'layer', 'table', 'laydate', 'rmpmultipleselect'], function() {
        var element = layui.element,
                form = layui.form,
                layuitable = layui.table,
                multipleselect = layui.rmpmultipleselect,
                layer = layui.layer,
                laydate = layui.laydate;
        //当前正在查看的文件
        var  currentViewFile;

        //初始化模板
        var reportFileServerInfoViewTpl = templates["report-file-server-infos-tpl"];

        //初始化文件table
        var table = $('#rmp-report-history-table .layui-table').on('preXhr.dt', function( e, settings, data){
            globalLoadIndex = layer.msg('正在加载数据...', {icon:16, time:99999999, shade:0});
        }).on('init.dt', function(){
            layer.close(globalLoadIndex);
        }).on('draw.dt', function(){
            layer.close(globalLoadIndex);
        }).DataTable($.extend(true, {}, DT_CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
            "columnDefs": [{"orderable":false, "aTargets":[0, 7]}],
            "ajax":REPORT_HISTORY_FILE_LIST_URL + '?userKey=' + userKey,
            "columns":[
                {
                    "data": null,
                    "render": function(data) {
                        return '<input type="checkbox">';
                    }
                },
                {
                    "data":"id"
                },
                {
                    "data":"fileName"
                },
                {
                    "data":'serverCount',
                    "render":function(data) {
                        return '<button class="layui-btn layui-btn-sm layui-btn-danger view-server-infos">&nbsp;' + data + '&nbsp;</button>';
                    }
                },
                {
                    "data":'infoCount'
                },
                {
                    "data":"createTime"
                },
                {
                    "data":"fileSize"
                },
                {
                    "data":"mark"
                },
                {
                    "data":null,
                    "render":function(data) {
                        var html = '<button type="button" class="layui-btn layui-btn-sm view-file">视图</button>'
                                + '<button type="button" class="layui-btn layui-btn-sm download-file">下载</button>'
                                + '<button type="button" class="layui-btn layui-btn-sm del-file">删除</button>';
                        return html;
                    }
                }
            ]
        }));

        //初始化详情视图
        $(".rmp-monitoring-content > .layui-collapse").append(templates["monitoring-content-table-tpl"]);
        $(".layui-colla-icon-refresh").remove();
        element.render('collapse');

        //初始化laydate组件
        $(".rmp-report-advanced-query input[lay-datetime]").each(function(i, n){
            laydate.render({
                elem: n,
                type:'datetime',
                range:'~'
            });
        });

        /********************************************* Form提交监听 ************************************************************************/
        //高级查询提交
        form.on('submit(advanced-query-submit)', function(data){
            var url = REPORT_HISTORY_FILE_LIST_URL + "?userKey=" + userKey
            $.each(data.field, function(key, value){
                rmputils.stringUtils.isNotEmpty(value) && (url += '&' + key + '=' + value);
            });
            table.ajax.url(url).load(function(){
                layer.msg('查询成功!', {icon:1, time:1500});
            }, true);

            return false;
        });

        //数据分析弹出页面下拉框监听
        form.on('select(analyze-server-type)', function(data){
            //初始化服务器选项的多选下拉框
            var serverListOptionsData = [];
            var itemNameOptionsData = [];
            $.each(fileData.serverList[data.value], function(i, info){
                serverListOptionsData.push({
                    text:((info.realHost == '' ? info.host : info.realHost) + ':' + info.port),
                    value:info.viewId
                });
            });
            $.each(serverInfos[data.value]['constant'], function(name, mark){
                itemNameOptionsData.push({
                    text:mark,
                    value:name
                });
            });
            window.analyzeServerListSelectObj != undefined && (window.analyzeServerListSelectObj.dom.html(''));
            window.analyzeItemNameSelectObj != undefined && (window.analyzeItemNameSelectObj.dom.html(''));

            window.analyzeItemNameSelectObj = multipleselect({
                ele:'#analyze-item-name',
                render:true,
                options:{
                    data:itemNameOptionsData,
                    tip:"选择需要展示的类目"
                },
                width:200
            });

            window.analyzeServerListSelectObj = multipleselect({
                ele:'#analyze-server-list',
                render:true,
                options:{
                    data:serverListOptionsData,
                    tip:"选择指定类型的服务器"
                },
                width:200
            });
        });

        //全选按钮
        form.on('checkbox(all-checked)', function(data) {
            $(data.elem).siblings('input').prop("checked",data.elem.checked);
            form.render('checkbox');
        });



        /***************************************************Jquery代理方式批量监听*********************************************************************************/
        $(document).delegates({
            //以组合表格的方式查看整体详情
            '.view-file':function(){
                currentViewFile = table.row($(this).parents('tr')).data();
                $.post(REPORT_HISTORY_GET_INFO_DATA_URL, {userKey:userKey, fileId:currentViewFile.id}, function(json){
                    validatReturnJson(json, function(){
                        fileData = json.data;
                        initDatatables();
                        toggleTableOrView('view');
                    });
                });
            },
            //下载文件
            '.download-file':function(){
                var data = table.row($(this).parents('tr')).data();
                window.open("../../" + data.filePath);
            },
            //删除文件
            '.del-file':function(){
                var that = this;
                layer.confirm('确认删除该历史记录文件吗？', {title:"提示", shadeClose:true}, function(index){
                    var data = table.row($(that).parents('tr')).data();
                    $.post(REPORT_HISTORY_FILE_DEL_URL, {userKey:userKey, fileId:data.id}, function(json){
                        validatReturnJson(json, function(){
                            table.row($(that).parents('tr')).remove().draw();
                            layer.msg('删除成功!');
                        });
                    });
                    layer.close(index);
                });

            },
            //查看当前文件中的保存的服务器信息
            '.view-server-infos':function(){
                var data = table.row($(this).parents('tr')).data();
                layer_show(data.fileName + '-监控的服务器信息', reportFileServerInfoViewTpl.render(JSON.parse(data.serverInfos)), 1100, (180 + 40 * data.serverCount), 1, function(layero, index){
                    layuitable.init('file-server-infos-table', {
                        initSort:{
                            field:'startTime', type: 'desc'
                        }
                    });
                });
            },

            //返回到历史记录
            '.rmp-monitoring-btn-tools button:eq(3)':function(){
                toggleTableOrView('file');
            },
            //返回查看详情视图
            '.rmp-monitoring-btn-tools button:eq(4)':function(){
                toggleTableOrView('view');
            },
            //数据分析
            '.rmp-monitoring-btn-tools button:eq(0)':function(){
                if (currentViewFile == undefined) {
                    layer.msg('请先选择一个文件进行详情视图查看!');
                    return false;
                }

                layer_show('数据分析', templates['rmp-report-history-analyze'], null, null, 1, function(layero, index){
                    //初始化select组件
                    form.render('select');
                    layero.find("#rmp-report-echarts-view").height(layero.height() - 160).width(layero.width() - 100);
                });



            },
            //高级查询
            '.rmp-monitoring-btn-tools button:eq(1)':function(){
                if ($("#rmp-report-history-table").hasClass('layui-hide')) {
                    layer.msg('请返回到文件列表!', {time:1500});
                    return false;
                }
                //$(this).toggleClass('layui-btn-lightgreen');
                $('.rmp-report-advanced-query').toggleClass('layui-hide');
            },
            //打开导出到excel的配置窗口
            '.rmp-monitoring-btn-tools button:eq(2)':function(){
                if (currentViewFile == undefined) {
                    layer.msg('请先选择一个文件进行详情视图查看!');
                    return false;
                }
                //需要设计用户可以自行配置将哪些内容经过哪些处理之后写入到excel
                layer_show('导出Excel设定', templates['rmp-report-history-export-setting'].render(fileData['serverList']), 1100, null, 1, function(layero, index){
                    window.exportSettingKind = multipleselect({
                        ele:'#export-setting-kind'
                    });

                    element.init('collapse');
                    form.render('checkbox');
                });

            },
            //刷新历史记录表格
            '.rmp-monitoring-btn-tools button:eq(5)':function(){
                if ($("#rmp-report-history-table").hasClass('layui-hide')) return false;
                table.ajax.url(REPORT_HISTORY_FILE_LIST_URL + "?userKey=" + userKey).load(null, false);
            },
            //动态数据通过echarts图表显示
            '.dynamic-data':function(){
                showEchartsView(this);
            },
            //报表分析
            '#analyze-view-submit':function(){

            },
            //导出excel
            '#send-export-request':function(){
            	if (window.exportSettingKind.selected.selectedValue.length < 1) {
            		layer.msg('请至少选择一种分析数据类别!', {time:2000});
            		return;
            	}
            	
                var serverObjs = $(".export-setting-server:checked");
                var typeItems = $(".export-setting-item:checked");

                var sendData = {
                    userKey:userKey,
                    serverList:null,
                    itemName:null,
                    constant:{},
                    fileId:currentViewFile.id,
                    valueKind:JSON.stringify(window.exportSettingKind.selected.selectedValue)
                };
                
                var serverList = [];
                var itemName = {};

                $.each(serverObjs, function(i, n) {
                    serverList.push({viewId:$(n).attr("data-id"), host:$(n).attr("title"), serverType:$(n).attr("data-type")});
                });

                $.each(typeItems, function(i, n) {
                    var type = $(n).attr("data-type");
                    itemName[type] == undefined && (itemName[type] = []);
                    itemName[type].push($(n).attr("data-value")); 
                    sendData['constant'][type] == undefined && (sendData['constant'][type] = serverInfos[type]['constant']);
                });   
                
                if (serverList.length < 1) {
                    layer.msg("请至少选择一个服务器!", {icon:5, time:2000});
                    return;
                }
                sendData.serverList = JSON.stringify(serverList);
                sendData.itemName = JSON.stringify(itemName);
                sendData.constant =  JSON.stringify(sendData.constant);	
                globalLoadIndex = layer.msg('正在生成文件...', {icon:16, time:9999999, shade:0.4});
                $.post(REPORT_HISTORY_ANALYZE_EXCEL_EXPORT_URL, sendData, function(json){
                    layer.close(globalLoadIndex);
                    validatReturnJson(json, function(){
                        window.open("../../" + json.data);
                    });
                });


            }
        });
        /****************************************************公用方法********************************************************************************/
        /**
         * 显示监控的详情视图还是文件列表？
         * @param mode  'file' - 文件列表表格  'view' - 视图表格
         */
        function toggleTableOrView(mode) {
            var fileTableBtn = $('.rmp-monitoring-btn-tools button:eq(4)');
            var detailViewBtn = $('.rmp-monitoring-btn-tools button:eq(3)');

            var fileTable = $('#rmp-report-history-table');
            var detailView = $('#rmp-report-monitoring-view');

            var queryForm = $('.rmp-report-advanced-query');

            if (mode == 'file') {
                fileTable.removeClass('layui-hide');
                detailView.addClass('layui-hide');
                fileTableBtn.removeClass('layui-hide');
                detailViewBtn.addClass('layui-hide');
            }

            if (mode == 'view') {
                detailView.removeClass('layui-hide');
                fileTable.addClass('layui-hide');
                fileTableBtn.addClass('layui-hide');
                detailViewBtn.removeClass('layui-hide');
                queryForm.addClass('layui-hide');
            }
        }

        /**
         * 初始化datatables表格
         * @param infoData
         */
        function initDatatables () {
            $.each(serverInfos.viewTypes, function(type, name){
                viewInstances[type] = {};
                var table = $('#' + type + ' .layui-table').DataTable($.extend(true, {}, DT_CONSTANT.DATA_TABLES.DEFAULT_OPTION,
                        serverInfos[type]['dtInitParameter'], {data:fileData['serverList'][type], ajax:null, destroy:true}));
                viewInstances[type]['table'] = table;
            });
        }

        /**
         * 展示echarts图表
         * @param elem 触发按钮节点
         */
        function showEchartsView(elem) {

            //获取节点上绑定的元素信息
            var serverType = $(elem).attr('server-type'); //weblogic
            var itemName = $(elem).attr('data-item');//jdbcInfo
            var dataName = $(elem).attr('data-name');//availableConnectionCount
            var dataId = $(elem).attr('data-id');//viewId

            //判断该指定类目是否已经有展示图表了
            /*            if ($("#" + serverType + "-" + itemName + "-" + dataName + "-" + dataId)) {
             return false;
             }*/

            //组装echarts配置数据
            var title = serverInfos[serverType]['constant'][dataName];
            var seriesData = fileData['infoData'][serverType][dataId][itemName][dataName];
            var times = fileData['infoData'][serverType][dataId]['time'];

            //是否为多类目折线图
            var mode = rmputils.arrayUtils.isArray(seriesData) ? false : true;

            var option = {};

            //标题,多类目折线图不需要标题
            if (!mode) {
                option.title = {
                    text: title,
                    x: 'center',
                    align: 'right',
                    top:'top',
                    textStyle:{
                        color:'#EF2203'
                    }
                };
            }

            //提示框触发类型
            option.tooltip = {
                trigger: 'axis'
            };

            //工具组件
            option.toolbox = {
                show: true,
                feature: {
                    dataView: {readOnly: true}, //数据视图
                    saveAsImage:{},// 保存为图片
                    dataZoom:{}
                }
            };

            //x轴定义
            option.xAxis = {
                type : 'category',
                boundaryGap: false,
                data : times,
                axisLine: {onZero: false}
            };

            //var YType = "value";

            /*            if(!mode && rmputils.numberUtils.isNum(seriesData[0])){
             //y轴定义
             option.yAxis = {
             type : "category",// Y轴的定义
             axisLine: {onZero: false},
             boundaryGap: false
             };
             }*/

            //y轴定义
            option.yAxis = {
                type : "value",// Y轴的定义
                max:'dataMax',
                boundaryGap: [0.1, 0.1]
            };

            //多类目折线图 图例组件
            if (mode) {
                option.legend = {
                    data:[]
                };
                $.each(seriesData, function(i, n) {
                    option.legend.data.push(i);
                });
            }

            //数据
            option.series = [];

            if (mode) {
                $.each(seriesData, function(i, n) {
                    option.series.push({
                        name:i,
                        type:'line',
                        smooth:true,
                        data:n
                    });
                });
            } else {
                option.series.push({
                    name:title,
                    type:'line',
                    smooth:true,
                    data: seriesData
                })
            }

            //显示页面层图表,同一个页面可显示多个视图
            var thisEcharts;
            var idOfInterval;
            layer_show(title, '<div class="rmp-monitoring-echarts-view" id="' + serverType + "-" + itemName + "-" + dataName + "-" + dataId + '"></div>',
                    880, 460, 1, function(){
                        thisEcharts = echarts.init(document.getElementById(serverType + "-" + itemName + "-" + dataName + "-" + dataId), 'shine');
                        thisEcharts.setOption(option);
                        idOfInterval = setInterval(function () {
                            thisEcharts.setOption(option);
                        }, userSetting.monitoring.refreshIntervalTime);
                    }, null, function(){
                        clearInterval(idOfInterval);
                    });
        }
    });
</script>
</body>
</html>